//
//  ChainNetAPIClient.m
//  Chain
//
//  Created by zhaosh on 2018/3/30.
//  Copyright © 2018年 zhaosh. All rights reserved.
//
#import "ChainNetAPIClient.h"
#import "ChainNetStatus.h"

@interface ChainNetAPIClient ()
@property(assign,nonatomic)BOOL sessionError;
@end

@implementation ChainNetAPIClient
+(ChainNetAPIClient *)sharedJsonClient{
    static ChainNetAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[ChainNetAPIClient alloc]init];
    });
    return _sharedClient;
}

-(instancetype)init{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self setup];
    return self;
}

+ (AFSecurityPolicy*)customSecurityPolicy{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = @[certData];
    return securityPolicy;
}

-(void)setup{
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    [self.requestSerializer setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json",@"text/html",@"application/xml", nil];
    
    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //    self.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    self.requestSerializer.timeoutInterval = 10;
    self.requestSerializer=[AFJSONRequestSerializer serializer];
    
    //加载设置https证书方法
    //    [self setSecurityPolicy:[FXNetAPIClient customSecurityPolicy]];
}

- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NSUInteger )NetworkMethod
                       andBlock:(void (^)(id data, NSError *error))block{
    if (![[ChainNetStatus sharedInstance] isNetworkReachable]) {
        [SVProgressHUD showInfoWithStatus:@"暂时没有网络,请检查你的网络设置"];
        block(nil,[NSError new]);
        return;
    }
    //log请求数据
    DebugLog(@"\n===========request===========\n%@:\n%@", aPath, params);
    aPath = [aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //设置请求头 sessionId and guserId
    if (SESSION_ID && USER_ID) {
        NSString * uid = USER_ID;
        NSString * sid = SESSION_ID;
        DebugLog(@"\n===========request===========\n%@:\n%@", uid, sid);
        [self.requestSerializer setValue:SESSION_ID forHTTPHeaderField:@"sessionId"];
        [self.requestSerializer setValue:[NSString stringWithFormat:@"%@",USER_ID] forHTTPHeaderField:@"guserId"];
        [self.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"gt"];//设置移动端的标识
    }
    //发起请求
    switch (NetworkMethod) {
        case Get:{
            [self GET:aPath parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                DebugLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                block(responseObject, nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                DebugLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                block(nil, error);
            }];
            break;
        }
        case Post:{
            [self POST:aPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                DebugLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                block(responseObject, nil);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                DebugLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                block(nil, error);
            }];
            
            break;}
        default:
            break;
    }
}

-(void)postRequestJsonDataWithPath:(NSString *)aPath withParams:(NSDictionary *)params withHeader:(NSDictionary *)header andBlock:(void (^)(id data, NSError *error))block{
    if (![[ChainNetStatus sharedInstance]isNetworkReachable]) {
         [SVProgressHUD showInfoWithStatus:@"暂时没有网络,请检查你的网络设置"];
        block(nil,[NSError new]);
        return;
    }
    //log请求数据
    DebugLog(@"===========request===========\n%@\n%@\n", aPath, params);
    NSString *urlStr = [aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
 
    NSMutableDictionary *headerDic = [NSMutableDictionary new];
    if(header){
        headerDic = [NSMutableDictionary dictionaryWithDictionary:header];
    }
    
    NSMutableDictionary*newParams = [NSMutableDictionary dictionaryWithDictionary:params];
    if (SESSION_ID && USER_ID) {
        NSString * uid = USER_ID;
        NSString * sid = SESSION_ID;
        DebugLog(@"\n===========request===========\n%@:\n%@", uid, sid);
       // [self.requestSerializer setValue:[NSString stringWithFormat:@"%@",USER_ID] forHTTPHeaderField:@"guserId"];
        [self.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"gt"];//设置移动端的标识
        
        [self.requestSerializer  setValue:SESSION_ID forHTTPHeaderField:@"sessionId"];
        if ([aPath stringByMatching:@"getNewsDetailInfo"]) {
            [newParams setObject:USER_ID forKey:@"userId"];
        }
    }
    
    [self POST:urlStr parameters:newParams progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DebugLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
        block(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"\n===========response===========\n%@:\n%@", aPath, error);
        block(nil, error);
    }];
}

- (BOOL)judgeSessionOverdueWithDic:(NSDictionary *)dic{
    NSString *status = [NSString stringWithFormat:@"%@",[dic valueForKeyPath:@"status"]];
    NSString *errorCode = [NSString stringWithFormat:@"%@",[dic valueForKeyPath:@"errorCode"]];
    if ([status isEqualToString:@"ERROR"] && [errorCode isEqualToString:@"3"]) {
        return YES;
    } else {
        return NO;
    }
}

+ (void)saveCookieData{
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *cookie in cookies) {
        // Here I see the correct rails session cookie
        DebugLog(@"\nSave cookie: \n====================\n%@", cookie);
    }
    
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: cookiesData forKey: @"cookies"];
    [defaults synchronize];
}

+ (void)removeCookieData{
    NSURL *url = [NSURL URLWithString:BASE_URL];
    if (url) {
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
        for (int i = 0; i < [cookies count]; i++) {
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
            DebugLog(@"\nDelete cookie: \n====================\n%@", cookie);
        }
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"cookies"];
    [defaults synchronize];
}

//upload image
- (void)uploadImage:(UIImage *)image path:(NSString *)path name:(NSString *)name
       successBlock:(void (^)(NSURLSessionDataTask *operation, id responseObject,NSMutableDictionary *prams))success
       failureBlock:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure
      progerssBlock:(void (^)(NSProgress * _Nonnull uploadProgress))progress{
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    //    if ((float)data.length/1024 > 1000) {
    //        data = UIImageJPEGRepresentation(image, 1024*1000.0/(float)data.length);
    //    }
    
    NSMutableDictionary *prams = [self getParm:image];
    
    NSString *timeStr = [Datetime getCurrentTimestamp];
    NSInteger randomNum = arc4random()%1000000;
    NSString *imageName = [NSString stringWithFormat:@"%@%ld.jpg",timeStr,(long)randomNum];
    DebugLog(@"\nuploadImageSize\n%@ : %.0f", imageName, (float)data.length/1024);
    
    [self POST:path parameters:prams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在此处添加要发送的文件   （原理：block回调）
        [formData appendPartWithFileData:data name:name fileName:imageName mimeType:@"image/jpeg"];
    }
      progress:^(NSProgress * _Nonnull uploadProgress) {
          if (progress) {
              progress(uploadProgress);
          }
      }
       success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           DebugLog(@"Success: %@ ***** %@", task.response, responseObject);
           
           success(task, responseObject, prams);
       }
       failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           DebugLog(@"Error: %@ ***** %@", task.response, error);
           if (failure) {
               failure(task, error);
           }
       }
     ];
}

//post参数
- (NSMutableDictionary *)getParm:(UIImage*)image
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    int  perMBBytes = 1024*1024;
    
    CGImageRef cgimage = image.CGImage;
    size_t bpp = CGImageGetBitsPerPixel(cgimage);
    size_t bpc = CGImageGetBitsPerComponent(cgimage);
    size_t bytes_per_pixel = bpp / bpc;
    long lPixelsPerMB  = perMBBytes/bytes_per_pixel;
    long totalPixel = CGImageGetWidth(image.CGImage)*CGImageGetHeight(image.CGImage);
    long totalFileMB = (totalPixel/lPixelsPerMB)*perMBBytes;
    NSString *size = [NSString stringWithFormat:@"%ld",totalFileMB];
    
    [dic setObject:size forKey:@"filesize"];
    NSString *width = [NSString stringWithFormat:@"%f",image.size.width];
    [dic setObject:width forKey:@"width"];
    
    [dic setObject:@"temp.jpg" forKey:@"filename"];
    return dic;
}
@end
